package OrderService

import (
	"context"
	"gdshop-font-api-go/app/request/OrderReq"
	"gdshop-font-api-go/app/response/CouponResp"
	"gdshop-font-api-go/app/service/CouponService"
	"gdshop-font-api-go/library/response"
	"github.com/gogf/gf/frame/g"
)

func getUseCoupon(ctx context.Context, parames *OrderReq.UseCoupon) ([]*CouponResp.Index, error) {
	// 取出我未使用的优惠券
	cList, err := CouponService.GetMyAvailable(ctx, int(parames.MemberId))
	if err != nil {
		return nil, err
	}

	// 判断符合当前商品的优惠券
	checkResults, err := CheckStore(ctx, &parames.SubmitItem, cList)
	if err != nil {
		g.Log().Error("UseCoupon => checkStore 错误：" + err.Error())
		return nil, err
	}
	var fanhui []*CouponResp.Index
	for _, c := range cList {
		tmp := &CouponResp.Index{
			Id:               c.Id,
			CanShare:         c.CanShare,
			CouponType:       c.CouponType,
			DiscountMoney:    int(c.DiscountMoney),
			DiscountRatio:    c.DiscountRatio,
			IsThreshold:      c.IsThreshold,
			ReceiveLimit:     c.ReceiveLimit,
			ReceiveTimeEnd:   c.ReceiveTimeEnd,
			ReceiveTimeStart: c.ReceiveTimeStart,
			ReceiveTimeType:  c.ReceiveTimeType,
			Remark:           c.Remark,
			ThresholdMoney:   int(c.ThresholdMoney),
			ThresholdNum:     c.ThresholdNum,
			TimeEnd:          c.TimeEnd,
			TimeStart:        c.TimeStart,
			TimeType:         c.TimeType,
			Title:            c.Title,
			UseGoodsType:     c.UseGoodsType,
			MemberCouponId:   c.MemberCouponId,
		}
		for _, item := range checkResults.UseCouponOrderSubs {
			if item.CouponId == c.Id {
				tmp.UseType = 1
				continue
			}
		}
		fanhui = append(fanhui, tmp)
	}
	return fanhui, nil
}

func getAvailableUseCoupon(ctx context.Context, parames *OrderReq.UseCoupon) ([]OrderReq.OrderSubCoupon, error) {
	// 取出我未使用的优惠券
	cList, err := CouponService.GetMyAvailable(ctx, int(parames.MemberId))
	if err != nil {
		return nil, err
	}
	// 判断符合当前商品的优惠券
	checkResults, err := CheckStore(ctx, &parames.SubmitItem, cList)
	if err != nil {
		g.Log().Error("UseCoupon => checkStore 错误：" + err.Error())
		return nil, err
	}
	return checkResults.UseCouponOrderSubs, nil
}

func UseCoupon(ctx context.Context, parames *OrderReq.UseCoupon) *response.JsonResponse {
	couponList, err := getUseCoupon(ctx, parames)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return response.SuccessByRequestMessageData(nil, "成功", couponList)
}
func getMyStatus(couponId int, id int) int {
	if couponId == id {
		return 1
	} else {
		return 0
	}
}
